//

// (  )
//

package com.tools.acceleratecore.logic.accelerate.memorydeepoptimizer.impl;

import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import com.tools.acceleratecore.AccelerateCoreFactory;
import com.tools.acceleratecore.logic.accelerate.memorydeepoptimizer.intf.IMemoryAnalyzer;
import com.tools.acceleratecore.logic.accelerate.process.intf.IProcessItem;
import com.tools.acceleratecore.logic.accelerate.process.intf.IProcessMgr;
import com.tools.acceleratecore.xlib.util.UtilApp;
import com.tools.acceleratecore.xlib.util.UtilHardware;
import com.tools.acceleratecore.xlib.util.UtilProcess;

public class MemoryAnalyzer implements IMemoryAnalyzer {
    private Context mContext = null;
    private IProcessMgr mIProcessMgr = null;
    private long mMemoryTotalSize = 0L;
    private static final long mMemory1G = 1073741824L;

    public MemoryAnalyzer() {
        this.mContext = AccelerateCoreFactory.getApplication();
        this._init();
    }

    private void _init() {
        this.mIProcessMgr = (IProcessMgr)AccelerateCoreFactory.getInstance().createInstance(IProcessMgr.class);
        this.mMemoryTotalSize = UtilHardware.getMemoryTotalSize() * 1024L;
    }

    public long getOptimizeMemorySize() {
        return this.analyzeOptimizeMemorySize();
    }

    private long analyzeOptimizeMemorySize() {
        long lSysAppUesSize = 0L;
        long lNormalAppUseSize = 0L;
        ActivityManager am = (ActivityManager)this.mContext.getSystemService("activity");
        MemoryInfo memoryInfoTotal = new MemoryInfo();
        am.getMemoryInfo(memoryInfoTotal);
        long lTotalFreeSize = memoryInfoTotal.availMem;
        this.mIProcessMgr.startScanProcessSyn();
        int nProcessItemCount = this.mIProcessMgr.getProcessItemCount();

        for(int nIndex = 0; nIndex < nProcessItemCount; ++nIndex) {
            IProcessItem iProcessItem = this.mIProcessMgr.queryProcessItem(nIndex);
            if(iProcessItem != null) {
                android.os.Debug.MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(new int[]{iProcessItem.getProcessID()});
                long lTotlaPss = (long)(memoryInfo[0].getTotalPss() * 1024);
                if(iProcessItem.getProcessID() == UtilProcess.getMyPID()) {
                    lNormalAppUseSize += lTotlaPss;
                } else if(UtilApp.isSystemApp(this.mContext, iProcessItem.getAppPackageName())) {
                    lSysAppUesSize += lTotlaPss;
                } else {
                    lNormalAppUseSize += lTotlaPss;
                }
            }
        }

        long lOptimizeMemorySize = lTotalFreeSize + lNormalAppUseSize;
        if(this.mMemoryTotalSize < 1073741824L) {
            lOptimizeMemorySize = (long)((double)lOptimizeMemorySize * 0.6D);
        }

        return lOptimizeMemorySize;
    }
}
